package com.ruoyi.system.controller;

import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.HmzInventoryDetail;
import com.ruoyi.system.domain.HmzItem;
import com.ruoyi.system.service.IHmzInventoryDetailService;
import com.ruoyi.system.service.IHmzItemService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 盘点单子Controller
 * 
 * @author ruoyi
 * @date 2024-10-30
 */
@RestController
@RequestMapping("/system/HmzInventoryDetail")
public class HmzInventoryDetailController extends BaseController
{
    @Autowired
    private IHmzInventoryDetailService hmzInventoryDetailService;

    @Autowired
    private IHmzItemService hmzItemService;

    /**
     * 查询盘点单子列表
     */
    @PreAuthorize("@ss.hasPermi('system:HmzInventoryDetail:list')")
    @GetMapping("/list")
    public TableDataInfo list(HmzInventoryDetail hmzInventoryDetail, Boolean showMissing)
    {
        // 如果有masterId参数且需要显示缺失记录，则进行特殊处理
        if (hmzInventoryDetail.getMasterId() != null && Boolean.TRUE.equals(showMissing)) {
            return listWithMissingRecords(hmzInventoryDetail);
        } else {
            // 普通查询，直接使用分页
            startPage();
            List<HmzInventoryDetail> list = hmzInventoryDetailService.selectHmzInventoryDetailList(hmzInventoryDetail);
            return getDataTable(list);
        }
    }
    
    /**
     * 查询包含缺失记录的盘点单子列表（带分页优化）
     */
    private TableDataInfo listWithMissingRecords(HmzInventoryDetail hmzInventoryDetail) {
        // 获取分页参数
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        
        // 1. 先查询现有的盘点记录（不分页，需要知道所有已有记录）
        List<HmzInventoryDetail> existingList = hmzInventoryDetailService.selectHmzInventoryDetailList(hmzInventoryDetail);
        
        // 2. 获取当前盘点单中已有的rfidCode集合
        Set<String> existingRfidCodes = existingList.stream()
            .map(HmzInventoryDetail::getRfidCode)
            .filter(rfidCode -> rfidCode != null)
            .collect(Collectors.toSet());
        
        // 3. 查询hmz_item表中goodsState=0的所有记录
        HmzItem itemQuery = new HmzItem();
        itemQuery.setGoodsState(0L); // 0表示在库
        List<HmzItem> inStockItems = hmzItemService.selectHmzItemList(itemQuery);
        
        // 4. 找出缺失的记录（限制数量以提高性能）
        List<HmzInventoryDetail> missingList = new ArrayList<>();
        int missingCount = 0;
        final int MAX_MISSING_RECORDS = 1000; // 限制缺失记录的最大数量
        
        for (HmzItem item : inStockItems) {
            if (missingCount >= MAX_MISSING_RECORDS) {
                break; // 限制缺失记录数量，避免性能问题
            }
            
            if (item.getRfidCode() != null && !existingRfidCodes.contains(item.getRfidCode())) {
                HmzInventoryDetail missingDetail = new HmzInventoryDetail();
                missingDetail.setMasterId(hmzInventoryDetail.getMasterId());
                missingDetail.setItemId(item.getId());
                missingDetail.setRfidCode(item.getRfidCode());
                missingDetail.setIsMissing(true);
                missingDetail.setRemark("缺失记录");
                missingList.add(missingDetail);
                missingCount++;
            }
        }
        
        // 5. 合并现有记录和缺失记录
        List<HmzInventoryDetail> allList = new ArrayList<>();
        allList.addAll(existingList);
        allList.addAll(missingList);
        
        // 6. 手动分页
        int total = allList.size();
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, total);
        
        List<HmzInventoryDetail> pageList;
        if (startIndex < total) {
            pageList = allList.subList(startIndex, endIndex);
        } else {
            pageList = new ArrayList<>();
        }
        
        // 7. 构造返回结果
        TableDataInfo dataTable = new TableDataInfo();
        dataTable.setCode(200);
        dataTable.setMsg("查询成功");
        dataTable.setRows(pageList);
        dataTable.setTotal(total);
        
        return dataTable;
    }

    /**
     * 导出盘点单子列表
     */
    @PreAuthorize("@ss.hasPermi('system:HmzInventoryDetail:export')")
    @Log(title = "盘点单子", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HmzInventoryDetail hmzInventoryDetail)
    {
        List<HmzInventoryDetail> list = hmzInventoryDetailService.selectHmzInventoryDetailList(hmzInventoryDetail);
        ExcelUtil<HmzInventoryDetail> util = new ExcelUtil<HmzInventoryDetail>(HmzInventoryDetail.class);
        util.exportExcel(response, list, "盘点单子数据");
    }

    /**
     * 获取盘点单子详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:HmzInventoryDetail:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(hmzInventoryDetailService.selectHmzInventoryDetailById(id));
    }

    /**
     * 新增盘点单子
     */
    @PreAuthorize("@ss.hasPermi('system:HmzInventoryDetail:add')")
    @Log(title = "盘点单子", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HmzInventoryDetail hmzInventoryDetail)
    {
        return toAjax(hmzInventoryDetailService.insertHmzInventoryDetail(hmzInventoryDetail));
    }

    /**
     * 修改盘点单子
     */
    @PreAuthorize("@ss.hasPermi('system:HmzInventoryDetail:edit')")
    @Log(title = "盘点单子", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HmzInventoryDetail hmzInventoryDetail)
    {
        return toAjax(hmzInventoryDetailService.updateHmzInventoryDetail(hmzInventoryDetail));
    }

    /**
     * 删除盘点单子
     */
    @PreAuthorize("@ss.hasPermi('system:HmzInventoryDetail:remove')")
    @Log(title = "盘点单子", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(hmzInventoryDetailService.deleteHmzInventoryDetailByIds(ids));
    }
}
